package com.sjs.boot.dynamic.facade.config;

import com.sjs.boot.dynamic.core.config.method.MethodConfig;
import com.sjs.boot.dynamic.facade.run.AbstractHandler;
import com.sjs.boot.dynamic.facade.run.AbstractResponser;
import com.sjs.boot.dynamic.util.ValParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/9 19:49
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
public abstract class AbstractResponseConfig {
    private static final Logger LOG = LoggerFactory.getLogger(AbstractResponseConfig.class);

    private static final int RESERVED_RESULTCODE = 1000;

    private static final String CONFIG_REASONS = "reasons";

    private Map<Integer, String> reasons = new HashMap<Integer, String>();
    private AbstractResponser responser = null;

    abstract protected boolean parseExt(String version, Map<String, Object> json, MethodConfig mc);

    public boolean parseConfig(String version, Map<String, Object> json, MethodConfig mc) {
        if (json == null) {
            return true; //使用默认的配置
        }
        AbstractResponser processor = (AbstractResponser) AbstractHandler.getHandler(json, mc.getResponser());
        if (processor == null) {
            LOG.error("Fail to read responser-processor of {}", mc.getName());
            return false;
        }

        mc.setResponser(processor);

        if (json.containsKey(CONFIG_REASONS)) {
            Map<String, Object> obj = ValParser.getAsObject(json, CONFIG_REASONS);
            int code;

            for (Map.Entry<String, Object> one : obj.entrySet()) {
                code = ValParser.parseInt(one.getKey(), -1);
                if (code <= RESERVED_RESULTCODE) {
                    LOG.error("Fail to parse reason-code:{}, must be bigger than {}", one.getKey(), RESERVED_RESULTCODE);
                    return false;
                }
                reasons.put(code, one.getValue().toString());
            }
        }
        return parseExt(version, json, mc);
    }

    public void setResponser(AbstractResponser responser) {
        this.responser = responser;
    }

    public AbstractResponser setResponser() {
        return responser;
    }

    public Map<Integer, String> getReasons() {
        return reasons;
    }

    public String getReason(int resultCode) {
        return reasons.get(resultCode);
    }


    /**
     * 是否需要框架处理返回信息
     *
     * @return
     */
    public boolean isNeedResponse() {
        return true;
    }

    //override it when need it
    public void destroy() {
    }
}
